//
//  XYMScanViewController.m
//  healthcoming
//
//  Created by jack xu on 16/11/15.
//  Copyright © 2016年 Franky. All rights reserved.
//

#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height

#import "XYMScanViewController.h"
#import "XYMScanView.h"
#import <AVFoundation/AVFoundation.h>
#import "ActivePowerViewController.h"
#import "DeviceBrokenDownViewController.h"
#import "LightViewController.h"
#import "UpDatePowerVersonViewController.h"
#import "SendFactoryViewController.h"
#import "WriteCodeViewController.h"
#import "ScanQRCodeToGetPasswordViewController.h"


@interface XYMScanViewController ()<XYMScanViewDelegate,WriteCodeViewControllerDelegate>
{
    int line_tag;
    UIView *highlightView;
    NSString *scanMessage;
    BOOL isRequesting;
}

@property (nonatomic,weak) XYMScanView *scanV;
@property (nonatomic,strong) MBProgressHUD *hub;
@end

@implementation XYMScanViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];;

    XYMScanView *scanV = [[XYMScanView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) withVC:self];
    scanV.delegate = self;
    [scanV creatTextViewByText:_contentString];
    [scanV creatLightButtonByType:_type];
    [self.view addSubview:scanV];
    _topView.backgroundColor = kClearColor;
    [self.view bringSubviewToFront:_topView];
    _scanV = scanV;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCode:) name:@"qrcode" object:nil];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}


- (void)getCode:(NSNotification*)noti{
    NSString *qrcode = noti.object;
    [self getCodeFunByString:qrcode];
}

-(void)getScanDataString:(NSString*)scanDataString{
    
    
    [self getCodeFunByString:scanDataString];
}

- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}



- (IBAction)photosButtonClick:(UIButton *)sender {
//    kAlert(@"点击相册");
    [[TakePicDelegate defaultManager] jumpAlarmInViewController:self notiName:@"qrCode" type:@"1"];
}


- (void)getCodeFunByString:(NSString *)string{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] upLoadQRCodeInfoByEid:kUserId qrcode:string progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            NSDictionary *dict = responseBody[@"data"];
            NSString *codeString = dict[@"alias"];
            NSString *deviceType = dict[@"device_type"];//设备类型 1、WiFi 3、蓝牙 4、密码
            UIStoryboard *storyboard = kMainStroyboard;

            if (_type.integerValue == 102) {//激活充电宝
                ActivePowerViewController *activePowerVC = [storyboard instantiateViewControllerWithIdentifier:@"ActivePowerViewController"];
                
                activePowerVC.powerId = codeString;
                activePowerVC.typeValue = @"102";
                activePowerVC.deviceType = deviceType;
                [self.navigationController pushViewController:activePowerVC animated:YES];
            }else if (_type.integerValue == 104){//更新固件
                
                UpDatePowerVersonViewController*updatePowerVersonVC = [storyboard instantiateViewControllerWithIdentifier:@"UpDatePowerVersonViewController"];
                updatePowerVersonVC.powerId = codeString;
                [self.navigationController pushViewController:updatePowerVersonVC animated:YES];

            }else if (_type.integerValue == 107){//扫码充电
                
                if (deviceType.integerValue == 1) {
                    [self getPowerByCodeString:codeString];
//                }else if (deviceType.integerValue == 3){//蓝牙
                    
                }else if (deviceType.integerValue == 4){//密码
                    ScanQRCodeToGetPasswordViewController *getPasswordVC = [storyboard instantiateViewControllerWithIdentifier:@"ScanQRCodeToGetPasswordViewController"];
                    getPasswordVC.aliasNum = codeString;
                    [self.navigationController pushViewController:getPasswordVC animated:YES];
                }
                
                
                
            }else if (_type.integerValue == 108){//设备撤回
                
                [self chehuiFuncCodeString:codeString];
                
            }else if (_type.integerValue == 109){//设备故障
                
                DeviceBrokenDownViewController *deviceBDVC = [storyboard instantiateViewControllerWithIdentifier:@"DeviceBrokenDownViewController"];
                deviceBDVC.powerId = codeString;
                [self.navigationController pushViewController:deviceBDVC animated:YES];
                
            }else if (_type.integerValue == 110) {//变更充电宝 页面与激活充电宝一样
                
                ActivePowerViewController *activePowerVC = [storyboard instantiateViewControllerWithIdentifier:@"ActivePowerViewController"];
                
                activePowerVC.powerId = codeString;
                activePowerVC.typeValue = @"110";
                activePowerVC.deviceType = deviceType;
                
                [self.navigationController pushViewController:activePowerVC animated:YES];
                
            }else if (_type.integerValue == 111){//灯光控制
                
                if (deviceType.integerValue == 1) {
                    LightViewController *lightVC = [storyboard instantiateViewControllerWithIdentifier:@"LightViewController"];
                    lightVC.powerId = codeString;
                    [self.navigationController pushViewController:lightVC animated:YES];
                }else{
                    [self alertVCByTitle:@"该设备没有 [灯光控制] 功能"];
                }
   
            }else if (_type.integerValue == 112){//返厂
                [self sendFactoryWithCode:codeString];
            }

        }else{
            kAlert(responseBody[@"message"]);
            NSLog(@"%@",responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (void)chehuiFuncCodeString:(NSString *)codeString{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定撤回充电宝" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
    
    UIAlertAction *sureAction  =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self chehuiWithCode:codeString];
    }];
    [alert addAction:cancelAction];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)chehuiWithCode:(NSString *)codeString{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] recallPowerByEid:kUserId alias:codeString progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            [self alertVCByTitle:@"设备撤回成功"];
        }else{
            kAlert(responseBody[@"message"]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

//返厂
- (void)sendFactoryWithCode:(NSString *)codeString{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] getPowerErrorInfoByAlias:codeString eid:kUserId progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            NSDictionary *dic = responseBody[@"data"];
            SendFactoryModel *model = [[SendFactoryModel alloc] init];
            if (![dic isKindOfClass:[NSNull class]]) {
                [model setValuesForKeysWithDictionary:dic];
                if (![dic[@"employee"] isKindOfClass:[NSNull class]]) {
                    model.employee = dic[@"employee"];
                }
            }
            
            if ([BGFunctionHelper isNULLOfString:model.content]) {//如果内容是空
                NSString *title = @"该设备并未填写损坏详情，是否直接寄回工厂";
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }];
                UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self sendFacByCodeString:codeString];
                }];
                
                [alert addAction:action];
                [alert addAction:action2];

                [self presentViewController:alert animated:YES completion:nil];
            }else{
                UIStoryboard *storyboard = kMainStroyboard;
                SendFactoryViewController *sendFactoryVC = [storyboard instantiateViewControllerWithIdentifier:@"SendFactoryViewController"];
                sendFactoryVC.powerId = codeString;
                sendFactoryVC.model = model;
                [self.navigationController pushViewController:sendFactoryVC animated:YES];
            }
            
        }else{
            kAlert(responseBody[@"message"]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (void)sendFacByCodeString:(NSString *)codeString{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    
    [[AFClient shareInstance] sendFactoryByEid:kUserId alias:codeString progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            [self alertVCByTitle:@"操作成功"];
        }else{
            [self alertVCByTitle:responseBody[@"message"]];
            
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

//通知充电
- (void)getPowerByCodeString:(NSString *)codeString{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] postNotiToGetPowerByEid:kUserId alias:codeString progressBlock:nil success:^(id responseBody) {

        if ([responseBody[@"code"] integerValue] == 200) {

            NSString *message_id = responseBody[@"data"];
            
            if (![BGFunctionHelper isNULLOfString:message_id]) {
                __block XYMScanViewController*weakSelf = self;
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));
                
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [self.hub hideAnimated:YES];
                    
                    [weakSelf checkMessageToPowerByMessageId:message_id tipString:@"您可以开始充电了"];
                });
                
            }else{
                [self alertVCByTitle:@"您可以开始充电了"];
            }
            
            
//            [self checkMessageToPowerByMessageId:message_id tipString:@"您可以开始充电了"];
//            [self alertVCByTitle:@"您可以开始充电了"];
        }else{
            [self.hub hideAnimated:YES];
            [self alertVCByTitle:responseBody[@"message"]];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

//检查链路
- (void)checkMessageToPowerByMessageId:(NSString *)messageId tipString:(NSString *)tipString{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] checkPostToPowerByMessage_id:messageId progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            [self alertVCByTitle:tipString];
        }else{
            [self alertVCByTitle:responseBody[@"message"]];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (void)alertVCByTitle:(NSString *)title{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }];
    
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)getButtonClickWithType:(NSString *)typeValue{
    UIStoryboard *storyboard = kMainStroyboard;
    WriteCodeViewController *writeVC = [storyboard instantiateViewControllerWithIdentifier:@"WriteCodeViewController"];
    writeVC.typeString = typeValue;
    writeVC.delegate = self;
    [self.navigationController pushViewController:writeVC animated:YES];
}

#pragma mark - writeCodeDelegate
- (void)getWriteCodeType:(NSString *)type codeString:(NSString *)codeString{
    [self findWritePowerByCode:codeString type:type];
}

- (void)findWritePowerByCode:(NSString *)codeString type:(NSString *)type{
    [self.hub hideAnimated:YES];
    
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] findPowerWriteByEid:kUserId alias:codeString progressBlock:nil success:^(id responseBody) {
        if ([responseBody[@"code"] integerValue] == 200) {
            [self.hub hideAnimated:YES];

            if (type.integerValue == 1) {
                //撤回
                [self chehuiFuncCodeString:codeString];
            }else{
                //返厂
                [self sendFactoryWithCode:codeString];
            }
        }else{
            kAlert(responseBody[@"message"]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

@end
